package com.ssl.admin.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCommonProcessor {
    @Autowired
    private RedisTemplate redisTemplate;
    public Object get(String key) {
        if(key == null) {
            throw new UnsupportedOperationException("Redis key could not be null!");
        }
        return redisTemplate.opsForValue().get(key);
    }
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }
    public void set(String key, Object value, long time) {
        if (time > 0) {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        } else {
            set(key, value);
        }
    }
    public void remove(String key) {
        redisTemplate.delete(key);
    }

    //加锁
    public boolean getLock(String key, String uuid, long timeout, TimeUnit timeUnit) {
        Boolean locked = redisTemplate.opsForValue().setIfAbsent(key, uuid, timeout, timeUnit);
        return locked;
    }

    //解锁。直接delete掉这个key。可以，不好。还是采用 lua 脚本，保证原子一致性。
    // 今天趁着高兴，我们写一个lua脚本去删除我们锁。
    public Long runLuaScripts(String luaScripts, String uuid, String key) {
        DefaultRedisScript redisScript = new DefaultRedisScript(luaScripts, Long.class);
        Object result = redisTemplate.execute(redisScript, Collections.singletonList(key), uuid);
        return (Long) result;
    }
}